import random

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.sms.tasks import send_sms_code
from verifications import constants

# get /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    def get(self, request, mobile):

        redis_conn = get_redis_connection('sms_code')
        if redis_conn.get('sms_security_%s'% mobile):
            return Response({'message': '验证码请求频繁'}, status=status.HTTP_403_FORBIDDEN)
        # 自定义六位数验证码
        security_code = '%06d'% (random.randint(0,999999))
        redis_line = redis_conn.pipeline()
        redis_line.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, security_code)
        redis_line.setex('sms_security_%s'% mobile, constants.SEND_SMS_CODE_INTERVAL, constants.SEND_SMS_TEMP_ID)
        redis_line.execute()
        import logging
        log = logging.getLogger('django')
        log.error('验证码为---%s' % security_code)
        # 发送短信验证码
        # send_sms_code.delay(mobile, security_code)
        return Response({'message':'OK'})

